<?php
declare(strict_types=1);

namespace app\controller;

use app\BaseController;
use app\model\UserModel;
use think\facade\Db;
use think\facade\Validate;

class Xiaoshoudingdan extends BaseController
{
    /**
     * 成功返回
     */
    protected function success($msg = '', $data = null)
    {
        return json([
            'code' => 1,
            'message' => $msg,
            'data' => $data
        ]);
    }

    /**
     * 失败返回
     */
    protected function error($msg = '', $data = null)
    {
        return json([
            'code' => 0,
            'message' => $msg,
            'data' => $data
        ]);
    }

    /**
     * 获取订单列表
     */
    public function getList()
    {
        $page = input('pageNo', 1, 'intval');
        $limit = input('pageSize', 20, 'intval');
        $dingdan_code = input('dingdan_code', '');
        $customer_name = input('customer_name', '');
        $dingdan_status = input('dingdan_status', '');


        $user = $this->getUserInfo();
        $where = [];
        $where[] = ['o.user_id', '=', $user['id']];
        if (!empty($dingdan_code)) {
            $where[] = ['o.dingdan_code', 'like', "%{$dingdan_code}%"];
        }
        if (!empty($customer_name)) {
            $where[] = ['c.customer_name', 'like', "%{$customer_name}%"];
        }
        if (!empty($dingdan_status)) {
            $where[] = ['o.dingdan_status', '=', $dingdan_status];
        }


        $count = Db::name('dingdan')
            ->alias('o')->leftJoin('customer c', 'c.id = o.customer_id')
            ->where($where)->count();

        $list = Db::name('dingdan')
            ->alias('o')->leftJoin('customer c', 'c.id = o.customer_id')
            ->field('o.*,c.customer_name customer_name,c.phone1 customer_phone')
            ->where($where)
            ->order('o.id', 'desc')
            ->page($page, $limit)
            ->select()
            ->toArray();

        foreach ($list as &$item) {
            $item['sales_person'] = UserModel::where('id', $item['user_id'])->value('realname');
        }

        return $this->success('获取成功', [
            'list' => $list,
            'total' => $count
        ]);
    }

    /**
     * 添加或编辑订单
     */
    public function doEdit()
    {
        $data = input('post.');

        // 验证数据
        $rule = [
            'dingdan_code' => 'require',
            'dingdan_date' => 'require|date',
            'product_type' => 'require',
            'product_name' => 'require',
            'customer_name' => 'require',
            'quantity' => 'require|number',
            'sales_person' => 'require',
            //'department' => 'require',
            //'manager_approval' => 'require'
        ];

        $message = [
            'dingdan_code.require' => '订单编号不能为空',
            'dingdan_date.require' => '订单日期不能为空',
            'dingdan_date.date' => '订单日期格式不正确',
            'product_type.require' => '产品类型不能为空',
            'product_name.require' => '产品名称不能为空',
            'customer_name.require' => '客户姓名不能为空',
            'quantity.require' => '数量不能为空',
            'quantity.number' => '数量必须为数字',
            'sales_person.require' => '销售员不能为空',
            //'department.require' => '所属部门不能为空',
            //'manager_approval.require' => '部门主管审核不能为空'
        ];

        $validate = Validate::rule($rule)->message($message);
        if (!$validate->check($data)) {
            return $this->error($validate->getError());
        }

        // 处理日期格式
        if (isset($data['dingdan_date']) && !empty($data['dingdan_date'])) {
            $data['dingdan_date'] = date('Y-m-d', strtotime($data['dingdan_date']));
        }

        // 处理交货日期，如果为空则设置为NULL
        if (isset($data['delivery_date'])) {
            if (!empty($data['delivery_date'])) {
                $data['delivery_date'] = date('Y-m-d', strtotime($data['delivery_date']));
            } else {
                $data['delivery_date'] = null; // 设置为NULL而不是空字符串
            }
        }

        // 设置时间
        $now = date('Y-m-d H:i:s');

        if (isset($data['id']) && $data['id'] > 0) {
            // 编辑订单
            $id = $data['id'];
            unset($data['id']);
            $data['update_time'] = $now;

            $result = Db::name('dingdan')->where('id', $id)->update($data);
            if ($result !== false) {
                return $this->success('编辑成功', ['id' => $id]);
            } else {
                return $this->error('编辑失败');
            }
        } else {
            // 添加订单
            $data['create_time'] = $now;
            $data['update_time'] = $now;

            // 检查订单编号是否已存在
            $exists = Db::name('dingdan')->where('dingdan_code', $data['dingdan_code'])->find();
            if ($exists) {
                return $this->error('订单编号已存在');
            }

            $id = Db::name('dingdan')->insertGetId($data);
            if ($id) {
                return $this->success('添加成功', ['id' => $id]);
            } else {
                return $this->error('添加失败');
            }
        }
    }

    /**
     * 删除订单
     */
    public function doDelete()
    {
        $id = input('post.id', 0, 'intval');
        $ids = input('post.ids', '');

        if (empty($id) && empty($ids)) {
            return $this->error('参数错误');
        }

        // 开启事务
        Db::startTrans();
        try {
            if (!empty($id)) {
                // 删除订单
                Db::name('dingdan')->where('id', $id)->delete();
                // 删除关联的BOM清单
                Db::name('dingdan_bom')->where('order_id', $id)->delete();
            } else {
                // 处理多个ID
                $idArr = is_array($ids) ? $ids : explode(',', (string)$ids);
                // 删除订单
                Db::name('dingdan')->whereIn('id', $idArr)->delete();
                // 删除关联的BOM清单
                Db::name('dingdan_bom')->whereIn('order_id', $idArr)->delete();
            }

            // 提交事务
            Db::commit();
            return $this->success('删除成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error('删除失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取客户详情
     */
    public function getDetail()
    {
        $id = input('id', 0, 'intval');

        if ($id <= 0) {
            return $this->error('参数错误');
        }

        $info = Db::name('customer')->where('id', $id)->find();

        if ($info) {
            return $this->success('获取成功', $info);
        } else {
            return $this->error('客户不存在');
        }
    }

    /**
     * 获取所有客户负责人
     */
    public function getManagers()
    {
        $list = Db::name('user')
            ->field('id, realname')
            ->where('status', 1)
            ->select()
            ->toArray();

        return $this->success('获取成功', $list);
    }

    /**
     * 根据部门名称获取部门负责人
     */
    public function getDepartmentManagers()
    {
        $departmentName = input('department_name', '');

        if (empty($departmentName)) {
            return $this->error('部门名称不能为空');
        }

        // 先查询部门ID
        $department = Db::name('user_department')
            ->where('name', $departmentName)
            ->find();

        if (!$department) {
            return $this->error('部门不存在');
        }

        // 查询该部门的所有负责人
        $managers = Db::name('user_department_relation')
            ->alias('r')
            ->join('user u', 'r.user_id = u.id')
            ->where('r.department_id', $department['id'])
            ->where('r.is_leading', 1) // 只查询部门负责人
            ->where('u.status', 1) // 只查询状态正常的用户
            ->field('u.id, u.realname')
            ->select()
            ->toArray();

        return $this->success('获取成功', $managers);
    }

    /**
     * 获取订单BOM清单
     */
    public function getBomList()
    {
        $productId = input('product_id/d', 0);
        $page = input('page/d', 1);
        $pageSize = input('pageSize/d', 20);

        if (empty($productId)) {
            return $this->error('请选择产品');
        }

        try {
            // 查询产品是否存在
            $product = Db::name('product')->where('id', $productId)->find();

            if (!$product) {
                return $this->error('产品不存在');
            }

            // 查询BOM清单，关联物料表获取物料名称和编码
            $list = Db::name('product_bom')
                ->alias('pb')
                ->join('material_category mc', 'pb.material_id = mc.id', 'left')
                ->field('pb.*, mc.material_name, mc.material_code, mc.current_quantity as stock_quantity')
                ->where('pb.product_id', $productId)
                ->page($page, $pageSize)
                ->order('pb.id', 'asc')
                ->select()
                ->toArray();

            $count = Db::name('product_bom')
                ->where('product_id', $productId)
                ->count();

            return $this->success('获取成功', $list);
        } catch (\Exception $e) {
            Log::error('获取产品BOM清单异常: ' . $e->getMessage());
            return $this->error('获取BOM清单失败: ' . $e->getMessage());
        }
    }

    /**
     * 批量保存订单BOM清单
     */
    public function saveBomList()
    {
        $data = input('post.');

        if (empty($data['order_id']) || !isset($data['bom_list']) || !is_array($data['bom_list'])) {
            return $this->error('参数错误');
        }

        $orderId = $data['order_id'];
        $bomList = $data['bom_list'];

        // 开启事务
        Db::startTrans();
        try {
            // 先删除原有BOM清单
            Db::name('dingdan_bom')->where('order_id', $orderId)->delete();

            // 插入新的BOM清单
            foreach ($bomList as $item) {
                // 验证必要字段
                if (empty($item['material_id'])) {
                    continue;
                }

                $bomData = [
                    'order_id' => $orderId,
                    'material_id' => $item['material_id'],
                    'quantity' => $item['quantity'] ?? 1,
                    'create_time' => date('Y-m-d H:i:s')
                ];

                Db::name('dingdan_bom')->insert($bomData);
            }

            // 提交事务
            Db::commit();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error('保存失败: ' . $e->getMessage());
        }
    }

    /**
     * 添加或编辑订单BOM项
     */
    public function doEditBom()
    {
        $data = input('post.');

        // 验证数据
        $rule = [
            'order_id' => 'require|number',
            'material_id' => 'require|number',
            'quantity' => 'require|number'
        ];

        $message = [
            'order_id.require' => '订单ID不能为空',
            'order_id.number' => '订单ID必须为数字',
            'material_id.require' => '物料ID不能为空',
            'material_id.number' => '物料ID必须为数字',
            'quantity.require' => '数量不能为空',
            'quantity.number' => '数量必须为数字'
        ];

        $validate = Validate::rule($rule)->message($message);
        if (!$validate->check($data)) {
            return $this->error($validate->getError());
        }

        // 检查物料是否存在
        $material = Db::name('material_category')->where('id', $data['material_id'])->find();
        if (!$material) {
            return $this->error('物料不存在');
        }

        // 检查订单是否存在
        $order = Db::name('dingdan')->where('id', $data['order_id'])->find();
        if (!$order) {
            return $this->error('订单不存在');
        }

        if (isset($data['id']) && $data['id'] > 0) {
            // 编辑
            $id = $data['id'];
            unset($data['id']);
            $data['update_time'] = date('Y-m-d H:i:s');

            $result = Db::name('dingdan_bom')->where('id', $id)->update($data);
            if ($result) {
                return $this->success('编辑成功');
            } else {
                return $this->error('编辑失败');
            }
        } else {
            // 添加
            $data['create_time'] = date('Y-m-d H:i:s');

            $id = Db::name('dingdan_bom')->insertGetId($data);
            if ($id) {
                return $this->success('添加成功', ['id' => $id]);
            } else {
                return $this->error('添加失败');
            }
        }
    }

    /**
     * 删除订单BOM项
     */
    public function doDeleteBom()
    {
        $ids = input('post.ids', '');

        if (empty($ids)) {
            return $this->error('参数错误');
        }

        // 处理不同类型的输入
        if (is_numeric($ids)) {
            // 单个ID
            $result = Db::name('dingdan_bom')->where('id', $ids)->delete();
        } else {
            // 多个ID，逗号分隔的字符串
            $idArr = explode(',', (string)$ids);
            $result = Db::name('dingdan_bom')->whereIn('id', $idArr)->delete();
        }

        if ($result) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }
} 